package cn.edu.cqut.base.activity;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.TabActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Color;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;
import android.widget.Toast;
import cn.edu.cqut.base.util.AppUtil;

/**
 * 公共的TabActivity,最多支持5个RadioButton显示
 * 
 * @author chenliang
 * @version v1.1
 * @date 2014-2-23
 * 
 */
public abstract class BaseTabActivity extends TabActivity {

	protected static final String TAB1 = "TAB1";
	protected static final String TAB2 = "TAB2";
	protected static final String TAB3 = "TAB3";
	protected static final String TAB4 = "TAB4";
	protected static final String TAB5 = "TAB5";
	private static final int MAX_TAB = 4;
	// 按两次退出程序
	private int backCount = 0;
	// 默认为0 0代表不会退出 1代表按两次退出 2代表弹出提示框
	private int backMode = 0;
	protected static final int BACK_MODE_2COUNT = 1;
	protected static final int BACK_MODE_DIALOG = 2;

	protected TabHost tabHost = null;

	List<TextView> textViews = new ArrayList<TextView>();
	List<TextView> textBgs = new ArrayList<TextView>();
	List<View> layouts = new ArrayList<View>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		getWindow().setSoftInputMode(
				WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
						| WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		setContentView(R.layout.base_tab);
		initView();
	}

	protected void initView() {
		tabHost = getTabHost();

		TextView textView1 = (TextView) findViewById(R.id.textView1);
		TextView textView2 = (TextView) findViewById(R.id.textView2);
		TextView textView3 = (TextView) findViewById(R.id.textView3);
		TextView textView4 = (TextView) findViewById(R.id.textView4);
		textViews.add(textView1);
		textViews.add(textView2);
		textViews.add(textView3);
		textViews.add(textView4);

		TextView bg1 = (TextView) findViewById(R.id.text1);
		TextView bg2 = (TextView) findViewById(R.id.text2);
		TextView bg3 = (TextView) findViewById(R.id.text3);
		TextView bg4 = (TextView) findViewById(R.id.text4);
		textBgs.add(bg1);
		textBgs.add(bg2);
		textBgs.add(bg3);
		textBgs.add(bg4);

		View layout1 = (View) findViewById(R.id.layout1);
		View layout2 = (View) findViewById(R.id.layout2);
		View layout3 = (View) findViewById(R.id.layout3);
		View layout4 = (View) findViewById(R.id.layout4);
		layouts.add(layout1);
		layouts.add(layout2);
		layouts.add(layout3);
		layouts.add(layout4);
		ClickListener listener = new ClickListener();
		for (View view : layouts) {
			view.setOnClickListener(listener);
		}
		init();
	}

	/**
	 * 初始化TabActivity的时候调用，在里面必须调用setTabs
	 */
	public abstract void init();

	/** 设置当前显示的Tab */
	public void setCurrentTabByTag(String tab) {
		tabHost.setCurrentTabByTag(tab);
	}

	/**
	 * 设置Tab中的Actvity,图标,文本
	 * 
	 * @param tabs
	 *            每一个面板显示的Activity
	 * @param icons
	 *            图标,如果没有图标者设置对应位置为-1
	 * @param texts
	 *            文本内容
	 */
	public void setTabs(Class[] tabs, String[] texts) {
		if (tabs.length > MAX_TAB || texts.length > MAX_TAB) {
			return;
		}

		for (int i = 0; i < tabs.length; i++) {
			TabSpec ts = tabHost.newTabSpec("TAB" + (i + 1))
					.setIndicator("TAB" + (i + 1))
					.setContent(new Intent(BaseTabActivity.this, tabs[i]));
			tabHost.addTab(ts);

			layouts.get(i).setVisibility(View.VISIBLE);
			// 设置文本
			textViews.get(i).setText(texts[i]);
		}
		setCurrentTabByTag(TAB1);
	}

	/**
	 * 设置Tab中的Actvity,图标,文本
	 * 
	 * @param tabs
	 *            每一个面板显示的Activity
	 * @param icons
	 *            图标,如果没有图标者设置对应位置为-1
	 * @param texts
	 *            文本内容
	 */
	public void setTabs(Class[] tabs, String[] texts,
			List<Map<String, Object>> params) {
		if (tabs.length > MAX_TAB || texts.length > MAX_TAB) {
			return;
		}

		for (int i = 0; i < tabs.length; i++) {
			Intent intent = new Intent(BaseTabActivity.this, tabs[i]);
			if (params != null && params.get(i) != null) {
				for (Entry<String, Object> entry : params.get(i).entrySet()) {
					intent.putExtra(entry.getKey(), entry.getValue().toString());
				}
			}
			TabSpec ts = tabHost.newTabSpec("TAB" + (i + 1))
					.setIndicator("TAB" + (i + 1)).setContent(intent);
			tabHost.addTab(ts);

			layouts.get(i).setVisibility(View.VISIBLE);
			// 设置文本
			textViews.get(i).setText(texts[i]);
		}
		setCurrentTabByTag(TAB1);
	}

	protected void setColor(int index) {

		int selectColor = Color.rgb(0x00, 0x9F, 0xCC);
		int grayColor = Color.rgb(0xDC, 0xDC, 0xDC);
		int ghostWhiteColor = Color.rgb(0XF8, 0XF8, 0XFF);

		for (int i = 0; i < MAX_TAB; i++) {
			textViews.get(i).setTextColor(Color.BLACK);
			textBgs.get(i).setBackgroundColor(grayColor);
			layouts.get(i).setBackgroundColor(ghostWhiteColor);
		}
		textViews.get(index).setTextColor(selectColor);
		textBgs.get(index).setBackgroundColor(selectColor);
		layouts.get(index).setBackgroundColor(Color.WHITE);
	}

	class ClickListener implements OnClickListener {

		@Override
		public void onClick(View v) {
			int id = v.getId();
			switch (id) {
			case R.id.layout1:
				setCurrentTabByTag(TAB1);
				setColor(0);
				break;
			case R.id.layout2:
				setCurrentTabByTag(TAB2);
				setColor(1);
				break;
			case R.id.layout3:
				setCurrentTabByTag(TAB3);
				setColor(2);
				break;
			case R.id.layout4:
				setCurrentTabByTag(TAB4);
				setColor(3);
				break;
			default:
				break;
			}
		}

	}

	/**
	 * 设置退出模式
	 * 
	 * @param mode
	 *            BACK_MODE_2COUNT--按两次退出 BACK_MODE_DIALOG--弹出提示框退出
	 */
	public void setBackMode(int mode) {
		backMode = mode;
	}

	// 监听返回键
	public boolean dispatchKeyEvent(KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			if (backMode == BACK_MODE_2COUNT) {
				exitByCount();
			} else if (backMode == BACK_MODE_DIALOG) {
				exitByDialog();
			}
			// 默认
			else if (backMode == 0) {
				return super.dispatchKeyEvent(event);
			}
			return false;
		}

		return super.dispatchKeyEvent(event);
	};

	// 通过连续按两次退出程序
	public void exitByCount() {
		backCount++;
		if (backCount >= 2) {
			finish();
			System.exit(0);
		} else {
			Toast.makeText(getApplicationContext(), "再按一次回到桌面",
					Toast.LENGTH_SHORT).show();
			new Thread() {
				public void run() {
					try {
						Thread.sleep(2000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					backCount = 0;
				};
			}.start();
		}
	}

	// 通过弹出返回对话框退出程序
	public void exitByDialog() {
		AlertDialog.Builder builder = new Builder(this);
		builder.setMessage("确定要退出程序");
		builder.setIcon(android.R.drawable.ic_dialog_alert);
		builder.setTitle("提示");
		builder.setPositiveButton("确定",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
						finish();
						System.exit(0);
					}
				});
		builder.setNegativeButton("取消",
				new android.content.DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
		builder.create().show();
	}
}
